/*
 * Connection to the UALR tweet database
 */

package crypto;

//import java.sql.*;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;



/**
 *
 * @author Isaac Osesina 
 */

//Classes for connecting to the database
public class MySQLConnect {
    Connection conn;
    String url;
    String dbName;
    String driver ="com.mysql.jdbc.Driver";
;
    String userName;
    String password;

    public MySQLConnect(String url, String dbName, String userName, String password) {
        this.url = url;
        this.dbName = dbName;
        this.userName = userName;
        this.password = password;
    }

    public void connectToDB()
    {
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url+dbName,userName,password);
            System.out.println("Connected to the database");
          } catch (Exception e) {
            e.printStackTrace();
          }
    }

    public void disconectFromDB()
    {
         try {
            Class.forName(driver).newInstance();
            conn.close();
            System.out.println("Disconnected from database");
          } catch (Exception e) {
            e.printStackTrace();
          }
    }

    public String getMaxValue(String TableName, String FieldName) throws SQLException
    {
            Statement stmt = (Statement) conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT MAX(" + FieldName + ") AS MAXValue FROM " + TableName);
            if ( rs.next() ) {
                return rs.getString("MAXValue");
            }
            return null;
    }

    public void writeToDBTable(String dBTable, String WhatToWrite) throws SQLException
    {
        Statement statement = (Statement) conn.createStatement();
        String sql =  "INSERT INTO " + dBTable + " VALUES ("+ WhatToWrite +")";
        statement.executeUpdate( sql );
        //return statement.getResultSet();
    }

    public ResultSet runSQLStatement(String stmt) throws SQLException{
        Statement statement = (Statement) conn.createStatement();
        ResultSet executeQuery = statement.executeQuery(stmt);
        return executeQuery;
    }

    public Connection getConnection() {
        return conn;
    }

   
    public static void main(String[] args){
      // Connecting to the database -Make sure that you are also connected to the VPN
        MySQLConnect test = new MySQLConnect("jdbc:mysql://144.167.34.111/","twitterdatacopy", "cecilia" , "cecilia123");
       test.connectToDB();


    // Disconnection from the database
     //  test.disconectFromDB();
           }
    }
